#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlError>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_connectButton_clicked()
{
    QString host = ui->hostLineEdit->text();
    QString port = ui->portLineEdit->text();
    QString user = ui->userLineEdit->text();
    QString password = ui->passwordLineEdit->text();
    QString dbname = ui->dbnameLineEdit->text();

    db = QSqlDatabase::addDatabase("QPSQL");
    db.setHostName(host);
    db.setPort(port.toInt());
    db.setUserName(user);
    db.setPassword(password);
    db.setDatabaseName(dbname);

    // 使用密态等值查询来保护数据的私密性
    QString query = QString("SELECT * FROM table WHERE column = %1").arg(password);
    db.setUserName(user);
    db.setPassword(query);

    if (!db.open()) {
        QMessageBox::critical(this, "Error", db.lastError().text());
        return;
    }

    QSqlQuery sqlQuery(db);
    if (!sqlQuery.exec("SELECT * FROM table")) {
        QMessageBox::critical(this, "Error", sqlQuery.lastError().text());
        return;
    }

    ui->tableView->setModel(new QSqlQueryModel());
    ui->tableView->model()->setQuery(sqlQuery);
}